<template>
    <div class="content-panel pt-1">
        <el-tabs>
            <el-tab-pane label="基础信息">
                <div class="w-6p">
                    <base-form :fields="fields" v-model="model" :readonly="!editing" ref="formRef"></base-form>
                    <div class="text-center">
                        <el-button v-if="!editing" type="primary" icon="edit" @click="editing = true">编辑</el-button>
                        <template v-else>
                            <el-button @click="cancelEdit" icon="close">取消</el-button>
                            <el-button type="primary" @click="saveBaseInfo" icon="Checked">保存</el-button>
                        </template>
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="修改密码">
                <div class="w-6p">
                    <base-form :fields="pwdFields" v-model="pwdModel" ref="pwdFormRef" />
                    <div class="text-center">
                        <el-button type="primary" icon="Check" @click="updatePwd">保存</el-button>
                    </div>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script setup>
import { useSysStore } from "@/store/index.js";
import { watchEffect } from "vue";
import * as _ from "lodash";

const store = useSysStore();
const userInfo = computed(() => {
    return store.getUserInfo();
});
const model = ref({});
const fields = [
    { label: "头像", prop: "photo", type: "avatarUploader" },
    { label: "用户名", prop: "username", required: true, editable: false },
    { label: "昵称", prop: "nickname", required: true },
    { label: "手机号", prop: "phone", rquired: true },
    { label: "邮箱", prop: "email" },
];
const formRef = ref();
const pwdFields = [
    { label: "原密码", prop: "oldPassword", inputType: "password", required: true },
    { label: "新密码", prop: "password", inputType: "password", required: true },
    { label: "重复新密码", prop: "rePassword", inputType: "password", required: true },
];
const pwdModel = ref({});
const editing = ref(false);
const pwdFormRef = ref();

watchEffect(() => {
    model.value = _.cloneDeep(userInfo.value);
});

function cancelEdit() {
    model.value = _.cloneDeep(userInfo.value);
    editing.value = false;
}

function saveBaseInfo() {
    formRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https.post("/sys/user/update-mine", model.value).then(() => {
            app.success("操作成功");
            let a = _.assign({}, userInfo.value);
            a = _.assign(a, model.value);
            store.setUserInfo(a);
            editing.value = false;
        });
    });
}

function updatePwd() {
    pwdFormRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https.post("/sys/user/update-pwd", pwdModel.value).then(() => {
            ElMessage.success("密码更新成功");
        });
    });
}
</script>

<style lang="scss" scoped></style>
